﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Speech.Recognition;
using System.Windows.Forms;

namespace Voice2Text
{
    public partial class Fm_Main : Form
    {
        private int _thisTxtShowSecond = -1;
        private SpeechRecognitionEngine _speechRecognition = new SpeechRecognitionEngine();//创建语言识别对象
        public Fm_Main()
        {
            InitializeComponent();
            SetStyle();
            this.BackColor = Color.Black;
            this.TransparencyKey = this.BackColor;
        }

        private void SetStyle()
        {
            var xWidth = SystemInformation.PrimaryMonitorSize.Width;
            var yHeight = SystemInformation.PrimaryMonitorSize.Height;
            this.ClientSize = new Size(xWidth, 80);
            this.label.MaximumSize = new Size(xWidth, 80);
            this.label.MinimumSize = new Size(xWidth, 80);
            this.label.Size = new Size(xWidth, 80);
            this.Location = new Point(0, (yHeight / 6) * 5);
        }

        private void StartListening()
        {
            _speechRecognition.LoadGrammarAsync(new DictationGrammar());
            _speechRecognition.SetInputToDefaultAudioDevice();
            _speechRecognition.SpeechRecognized += SpeechRecognitionResponse;
            _speechRecognition.RecognizeAsync(RecognizeMode.Multiple);//启动
        }


        public void SpeechRecognitionResponse(object sender, SpeechRecognizedEventArgs e)
        {
            this.label.Text = e.Result.Text;
            _thisTxtShowSecond = 0;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            StartListening();
            timer.Start();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            if (_thisTxtShowSecond == 3)
            {
                this.label.Text = "";
                _thisTxtShowSecond = -1;
            }
            else if (_thisTxtShowSecond > -1)
            {
                _thisTxtShowSecond++;
            }
        }
    }
}